package de.gwtprime.client.widgets.trading.popup;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.event.OrderProcessedEvent;
import de.gwtprime.shared.requestFactory.OrderProxy;

public class OrderPaymentTriggeredPopup extends PopupPanel  {

	private static OrderPaymentTriggeredPopupUiBinder uiBinder = GWT
			.create(OrderPaymentTriggeredPopupUiBinder.class);

	interface OrderPaymentTriggeredPopupUiBinder extends
			UiBinder<Widget, OrderPaymentTriggeredPopup> {
	}
	
	
	@UiField Label descriptionLbl;
	@UiField Button paymentReceivedBtn;
	
	private ClientFactory clientFactory;
	private OrderProxy order;

	public OrderPaymentTriggeredPopup(ClientFactory clientFactory, OrderProxy order) {
		super(true, true); // auto hide and modal
		setWidget(uiBinder.createAndBindUi(this));
		
		this.clientFactory = clientFactory;
		this.order = order;
		
		descriptionLbl.setText("Zahlung angewiesen - Wenn die Zahlung eingeht, Bestätige die Zahlung");
	
		paymentReceivedBtn.setText("Zahlung erhalten");
	
	}
	
	@UiHandler("paymentReceivedBtn")
	public void onPaymentReceivedOnClick(ClickEvent e){
		paymentReceivedBtn.setEnabled(false);
		
		clientFactory.getEventBus().fireEvent(new OrderProcessedEvent(order));
		
		clientFactory.getRequestFactory().orderRequest().paymentReceived().using(order).fire(new Receiver<Void>() {
			@Override
			public void onSuccess(Void response) {
				
				clientFactory.getNotificationCenter().showMessage("Zahlung erhalten");
				
			}
			
			@Override
			public void onFailure(ServerFailure error) {
				Window.alert(error.getMessage()+error.toString());
			}
		
		});
		
	}

}
